package com.anolesoft.ProductRegistration.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.anolesoft.ProductRegistration.dto.*;
import com.anolesoft.ProductRegistration.service.ProductRegIstrationService;
import com.anolesoft.ProductRegistration.vo.ProductFabrecordVO;
import com.anolesoft.ProductRegistration.vo.ProductionRegistrationRecordVO;
import com.anolesoft.amljmes.test.fenguangyingdu.dto.FenguangYingduRecordQueryDTO;
import com.anolesoft.amljmes.test.fenguangyingdu.vo.FenguangYingduRecordExcelVO;
import com.anolesoft.amljmes.test.fenguangyingdu.vo.FenguangYingduRecordQueryVO;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.ProductRegistration.vo.ProductRegistrationQueryVO;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math3.analysis.function.Exp;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("/api/ProductRegistrationQuery")
public class ProductRegistrationController {
    @Autowired
    private ProductRegIstrationService productRegIstrationService;

    @GetMapping(value = "/list")
    public AjaxResult selectPageConditonList(ProductRegistrationQueryVO productRegistrationQueryVO) {
        log.debug("productRegistrationQueryVO：{}", productRegistrationQueryVO);
        Integer limit = productRegistrationQueryVO.getPageSize();
        Integer curr = productRegistrationQueryVO.getPageNo();
//        PageData<List<CrmBasePartPriceQueryDTO>> pageData = crmBasePartPriceService.selectPageConditionList(crmBasePartPriceQueryDTO, limit, curr);
//        List<CrmBasePartPriceQueryVO> vos = pageData.getItems().stream().map(t -> CustomBeanUtils.crmBasePartPriceQueryDTO2VO(t)).collect(Collectors.toList());
//        PageInfo<List<CrmBasePartPriceQueryVO>> pageInfo = new PageInfo<>(limit, pageData.getTotal(), vos);
        ProductRegistrationQueryDTO dto = BeanUtil.copyProperties(productRegistrationQueryVO, ProductRegistrationQueryDTO.class);
        log.debug("{}", dto);
        PageData<List<ProductRegistrationQueryDTO>> listPageData = this.productRegIstrationService.selectListByCondition(dto, limit, curr);
        List<ProductRegistrationQueryVO> vos = listPageData.getItems().stream().map(t -> BeanUtil.copyProperties(t, ProductRegistrationQueryVO.class)).collect(Collectors.toList());
        PageResult pg = new PageResult(vos, limit, curr, listPageData.getTotal());
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, pg);
    }

    @GetMapping(value = "/fabrecord")
    public AjaxResult selectPageConditonList(@RequestParam("zhizaojilutiaoma") String zhizaojilutiaoma) {
        ProductFabrecordDTO fabrecordDTO = productRegIstrationService.queryFabrecordByCode(zhizaojilutiaoma);
        if (Objects.isNull(fabrecordDTO)) {
            return new AjaxResult(HttpStatus.ERROR, "未找到对应制造记录！");
        }
        fabrecordDTO.setWasteNum("0");
        fabrecordDTO.setPassNumber(fabrecordDTO.getPutnum());
        fabrecordDTO.setQualifiedNumber("0");
        fabrecordDTO.setConcessionsTaste("0");
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, BeanUtil.copyProperties(fabrecordDTO, ProductFabrecordVO.class));
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ProductionRegistrationRecordFormVO {
        private List<ProductionRegistrationRecordVO> ProductRegistrationRecordVOs;
    }

    @PostMapping
    public AjaxResult saveBatch(@RequestBody List<ProductionRegistrationRecordVO> ProductRegistrationRecordVOs) {
        log.debug("save data:{}", ProductRegistrationRecordVOs);
        List<ProductReglstrationRecordDTO> dtos = ProductRegistrationRecordVOs.stream().map(t -> {
            ProductReglstrationRecordDTO dto = BeanUtil.copyProperties(t, ProductReglstrationRecordDTO.class);
            return dto;
        }).collect(Collectors.toList());
        this.productRegIstrationService.createBatch(dtos);
        return new AjaxResult(HttpStatus.SUCCESS, "保存成功");
    }

    @GetMapping(value = "/state")
    public AjaxResult IsState(@RequestParam("zhizaojilutiaoma") String zhizaojilutiaoma) {
        String count =this.productRegIstrationService.IsState(zhizaojilutiaoma);
        if (!"0".equals(count)) {
            return new AjaxResult(HttpStatus.ERROR, "此条码已存在外包完成返厂！");
        }
        return new AjaxResult(HttpStatus.SUCCESS, "");
    }
    @GetMapping(value = "/revocation")
    public AjaxResult revocation(@RequestParam("objuid") String objuid) {
        try {
            this.productRegIstrationService.revocation(objuid);
        }catch (Exception e){
            return new AjaxResult(HttpStatus.ERROR, e.getMessage());
        }
        return new AjaxResult(HttpStatus.SUCCESS,"撤回成功");
    }





    @PostMapping("/excel")
    public void export(ProductRegistrationQueryDTO productRegistrationQueryDTO, HttpServletResponse response) {
        ProductRegistrationQueryDTO dto = BeanUtil.copyProperties(productRegistrationQueryDTO, ProductRegistrationQueryDTO.class);
        PageData<List<ProductRegistrationQueryDTO>> listData = this.productRegIstrationService.selectListByCondition(dto,5000,1);

        List<ExportSheetsExcelDto> data = new ArrayList<>();
        for (int i = 0; i<listData.getItems().size(); i++) {
            ExportSheetsExcelDto excelDto = new ExportSheetsExcelDto();
            BeanUtils.copyProperties(listData.getItems().get(i),excelDto);
            int transfer = excelDto.getTransfer();
            if (transfer == 0) {
                excelDto.setTransferString("否");
            } else {
                excelDto.setTransferString("是");
            }
            data.add(excelDto);
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        try(OutputStream out = response.getOutputStream()) {
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("外包产品登记帐.xlsx").getBytes("gb2312"),"ISO8859-1"));
            EasyExcel.write(out, ExportSheetsExcelDto.class)
                    .registerConverter(new LocalDateTimeConverter())
                    .sheet("外包产品登记帐").doWrite(data);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String encodingFilename(String filename) {
        filename = CommonUtils.fastUUID() + "_" + filename + ".xlsx";
        return filename;
    }

/**
     * 获取下载路径
     *
     * @param filename 文件名称
     *//*
    private String getAbsoluteFile(String filename) {
        String downloadPath = SacmesConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }*/
}
